<?php
/**
 * Created by JetBrains PhpStorm.
 * User: GMC
 * Date: 10/3/13
 * Time: 2:20 PM
 * To change this template use File | Settings | File Templates.
 */

class WidgetMenu extends CWidget {
    public $categories, $id, $child_ids;

    public function init() {
        $id = isset($_GET['catalogid']) ? $_GET['catalogid'] : 0;

        $menu_cache = Yii::app()->cache->get('menu_cache');

        $update_menu = Yii::app()->session['update_menu'];
        if ($menu_cache == null || count($menu_cache) == 0 || (isset($update_menu) && $update_menu)) {
//            unset(Yii::app()->session['update_menu']);
            $catalogs = Catalog::model()->findAllByAttributes(array('parentid' => 0), array('order' => 'cat_order ASC'));


            $categories = array();
            foreach ($catalogs as $catalog) {
                $catalogChilds = Catalog::model()->findAllByAttributes(array('parentid' => $catalog->catalogid), array('order' => 'cat_order ASC'));
                if (count($catalogChilds) == 0) {
                    array_push($categories, array(
                        'id' => $catalog->catalogid,
                        'name' => '' . $catalog->catalogname,
                    ));
                } else {
                    $arr_child = array();
                    $arr_id = array();
                    foreach ($catalogChilds as $child) {
                        array_push($arr_child, array(
                            'id' => $child->catalogid,
                            'name' => $child->catalogname,
                        ));

                        array_push($arr_id, $child->catalogid);
                    }

                    array_push($categories, array(
                        'id' => $catalog->catalogid,
                        'name' => '' . $catalog->catalogname,
                        'childs' => $arr_child,
                        'child_ids' => $arr_id
                    ));
                }
            }
            $time = 60 * 60 * 24; //1 day is a time for reload new content
            Yii::app()->cache->set('menu_cache', $categories, $time);
        }
        $this->categories = Yii::app()->cache->get('menu_cache');
        $this->id = $id;
    }

    public function run() {
        return CWidget::render('widgetMenu', array('catalogs' => $this->categories, 'id' => $this->id));
    }
}